package com.lwt.codetop.binaryTree;

// 103. 二叉树的锯齿形层序遍历

import java.util.*;

/**
 *  思路：bfs，层序遍历拿到每一层的结果，高度从1开始的话，奇数层：顺序 偶数层：逆序
 */
public class BinaryTreeZigzagLevelOrderTraversal {
    public static void main(String[] args) {
        // 构建测试用例
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        // bfs
        List<List<Integer>> res =  bfs(root);
        System.out.println(res);
    }

    /**
     * bfs
     * @param root
     * @return
     */
    private static List<List<Integer>> bfs(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        int depth = 1;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()){
            int n = q.size();
            List<Integer> ceng = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                TreeNode node = q.poll();
                ceng.add(node.val);
                if(node.left != null) q.add(node.left);
                if(node.right != null) q.add(node.right);
            }
            if(depth % 2 == 0) Collections.reverse(ceng); // 逆序
            res.add(new ArrayList<>(ceng));
            depth += 1;
        }
        return res;
    }
}
